package com.caishi.lkx.user.api;

import cn.hutool.core.collection.CollUtil;
import com.caishi.lkx.common.BaseApi;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.exam.model.ExamModel;
import com.caishi.lkx.exam.model.IndustryModel;
import com.caishi.lkx.exam.service.IExamService;
import com.caishi.lkx.exam.service.impl.IndustryServiceImpl;
import com.caishi.lkx.exam.vo.IndexExamVo;
import com.caishi.lkx.exam.vo.IndexIndustryData;
import com.zzw.common.annotation.ApiTimeRecord;
import com.zzw.common.entity.impl.BaseEntity;
import com.zzw.common.utils.CommonUtil;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Tag(name = "首页接口")
@RestController
@RequestMapping("/user/home")
@Roles
public class IndexApi extends BaseApi {

    @Resource
    private IndustryServiceImpl industryService;

    @Resource
    private IExamService examService;

    @Operation(summary = "首页行业数据")
    @GetMapping("/industry-data")
    @ApiTimeRecord(gt = 500)
    public List<IndexIndustryData> index() {
        return industryService.indexDataV1();
    }

    @GetMapping("/industry-data-nocache")
    public List<IndexIndustryData> indexNoCache() {
        return industryService.noCacheIndexDataV1(false);
    }

    @Operation(summary = "首页热门数据")
    @GetMapping("/industry-data-bak")
    public List<IndexIndustryData> hotData() {
        List<IndustryModel> industryModels;
        if (!userContext.loginStatus() && userContext.currentLocalGroupId() != null) {
            var ids = industryService.groupPermission(userContext.currentLocalGroupId(), null, null);
            industryModels = industryService.selectList(industryService.wrappers()
                            .in(CollUtil.isNotEmpty(ids), BaseEntity::getId, ids)
                            .orderByAsc(IndustryModel::getSort)
                    , 2);
        } else {
            industryModels = industryService.hotIndustry();
        }
        return industryModels
                .stream().map(v -> {
                    var data = industryService.indexData(v.getId());
                    data.setName(v.getName());
                    data.setIndustryId(v.getId());
                    data.setIcon(v.getIcon());
                    return data;
                })
                .toList();
    }

    @Operation(summary = "首页热门考试数据")
    @GetMapping("/exam-data")
    @ApiTimeRecord(gt = 500)
    public IndexExamVo indexExam() {
        var lg = userContext.currentLocalGroupId();
        var ug = userContext.currentGroupId();
        var ui = userContext.currentUserId();
        var result = new IndexExamVo();
        List<String> permissionExam = null;
        List<String> permissionIndustry = null;
        if (!userContext.loginStatus() && lg != null) {
            permissionExam = examService.groupPermission(lg, null, null);
            permissionIndustry = industryService.groupPermission(lg, null, null);
            if (permissionExam != null && permissionExam.isEmpty()) permissionExam.add("-1");
            if (permissionIndustry != null && permissionIndustry.isEmpty()) permissionIndustry.add("-1");
        }
        var userExam = examService.userHaveExam(lg, ug, ui);
        var eg = userExam.getGroup().toArray(String[]::new);
        var eu = userExam.getUser().toArray(String[]::new);
        var ea = userExam.getAll().toArray(new String[0]);
        var userIndustry = industryService.userHaveIndustry(lg, ug, ui);
        var g = userIndustry.getGroup().toArray(String[]::new);
        var u = userIndustry.getUser().toArray(String[]::new);
        var a = userIndustry.getAll().toArray(String[]::new);
        result.setGjtk(examService.selectList(examService.wrapperProcessing(examService.wrappers()
                .in(CollUtil.isNotEmpty(permissionExam), BaseEntity::getId, permissionExam)
                .eq(ExamModel::getIndustryId, ExamModel.GJTK))));
        result.setZhiye(industryService.selectList(industryService.wrapperProcessing(industryService.wrappers().in(CollUtil.isNotEmpty(permissionIndustry), BaseEntity::getId, permissionIndustry))));
        result.getGjtk().sort(IndustryServiceImpl.permissionComparator(ea));
        result.getGjtk().forEach(v -> {
            var r = CommonUtil.binarySearch(eu, v.getId()) ? 0x01 : 0x00;
            v.setAuthFlag((byte) (r | (CommonUtil.binarySearch(eg, v.getId()) ? 0x02 : 0x00)));
        });
        result.getZhiye().sort(IndustryServiceImpl.permissionComparator(a));
        result.getZhiye().parallelStream().limit(4).forEach(v -> v.setExams(examService.selectList(examService.wrapperProcessing(examService.wrappers().eq(ExamModel::getIndustryId, v.getId())))));
        result.getZhiye().parallelStream().skip(4).forEach(v -> v.setExams(Collections.singletonList(examService.selectFirst(examService.wrapperProcessing(examService.wrappers().eq(ExamModel::getIndustryId, v.getId()))))));
        result.getZhiye().forEach(v -> {
            var r = CommonUtil.binarySearch(u, v.getId()) ? 0x01 : 0x00;
            v.setAuthFlag((byte) (r | (CommonUtil.binarySearch(g, v.getId()) ? 0x02 : 0x00)));
        });
        return result;
    }

    @Operation(summary = "首页试题 试卷数量")
    @GetMapping("/count")
    @ApiTimeRecord(gt = 500)
    public Object v2ConfigDetails() {
        return industryService.indexCountData();
    }

    @Operation(summary = "首页试题 试卷数量")
    @GetMapping("/count-nocache")
    public void v2ConfigDetailsNoCache() {
        industryService.indexCountDataExec(false);
    }

}
